package top.yaofengqiao.springcloudsimple.payment.biz.trigger.http.app;

import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.yaofengqiao.springcloudsimple.common.util.R;
import top.yaofengqiao.springcloudsimple.payment.biz.domain.pay.model.req.PaymentSuccessRequest;
import top.yaofengqiao.springcloudsimple.payment.biz.domain.pay.service.IPaymentService;
import top.yaofengqiao.springcloudsimple.payment.biz.trigger.http.app.dto.AliAsyncNotifyDTO;
import top.yaofengqiao.springcloudsimple.payment.biz.trigger.http.app.dto.PaymentApplyDTO;
import top.yaofengqiao.springcloudsimple.payment.biz.trigger.http.app.vo.PaymentApplyVO;
import top.yaofengqiao.springcloudsimple.web.starter.util.OauthUtil;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;

/**
 * @author yfq
 * @date 2024/6/14 17:20
 * @description
 */
@RestController
@RequestMapping("/appPayment")
public class AppPaymentController {
    @Resource
    private IPaymentService paymentService;

    /**
     * 发起订单支付申请，需要保证接口幂等
     */
    @PostMapping("/paymentApply")
    public R<PaymentApplyVO> paymentApply(@RequestBody @Validated PaymentApplyDTO paymentApplyDTO) {
        return R.ok(paymentService.paymentApply(paymentApplyDTO, OauthUtil.currentUserId()));
    }

    /**
     * 支付宝支付成功回调地址
     */
    @PostMapping("/alipayCallBack")
    public String alipayCallBack(AliAsyncNotifyDTO aliAsyncNotifyDTO) {
        // TODO 验签

        if (!"TRADE_SUCCESS".equals(aliAsyncNotifyDTO.getTrade_status())) return "success";

        // 支付成功处理
        PaymentSuccessRequest request = PaymentSuccessRequest.builder()
                .orderNo(aliAsyncNotifyDTO.getOut_trade_no())
                .tradeNo(aliAsyncNotifyDTO.getTrade_no())
                .payAmount(new BigDecimal(aliAsyncNotifyDTO.getBuyer_pay_amount()))
                .payTime(LocalDateTime.now())
                .build();
        boolean result = paymentService.paymentSuccessHandle(request);

        return result ? "success" : "fail";
    }

}
